package xm.erzhan.handlers;

import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import xm.erzhan.models.ResourceEntity;
import xm.erzhan.models.UserEntity;
import xm.erzhan.models.WarehouseEntity;
import xm.erzhan.models.responseModels.ResourceRes;
import xm.erzhan.repository.ResourceRepository;
import xm.erzhan.models.responseModels.NormRes;
import xm.erzhan.utils.Utils;
import javax.servlet.http.HttpServletRequest;
import xm.erzhan.controllers.ResourceController;
import xm.erzhan.utils.Code;
import xm.erzhan.controllers.UserController;
import xm.erzhan.models.reqModels.ResourceReq;

import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/resource")
public class ResoruceHandler {

    @Autowired
    private ResourceRepository resourceRepository;


    @Autowired
    private HttpServletRequest request;

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public @ResponseBody Map getResource() throws JSONException {

        NormRes normRes;

        normRes = Utils.checkToken(request.getHeader("access-token"));

        int code = normRes.getCode();
        if (code != 200) {
            Map map = new HashMap();
            map.put("code", Code.CodeEnum.getCodeByType("OK"));
            map.put("msg", normRes.getMsg());

            return map;
        }



        // get user info
        String UserName = normRes.getMsg();

        UserController userController = UserController.UserControllerShared();
        UserEntity user = userController.getUserByUserName(UserName);
        if (user == null) {
            Map map = new HashMap();
            map.put("code", Code.CodeEnum.getCodeByType("USER_NOT_EXIST"));
            map.put("msg", "user info not exis");

            return map;
        }


        // get resource info in cache
        ResourceController resourceController = ResourceController.resourceControllerShared();

        ResourceRes resourceRes = resourceController.getResourceEntitiesByPlayerId(user.getId());
        if (resourceRes != null) {

            String resSre = resourceController.getResourceBuildingsMap(resourceRes.getResourceEntity());

            String resourceStatusStr = resourceController.getResourceBuildingsStatus(resourceRes.getResourceEntity().getResourceBuildingsMap());

            resourceRes.getResourceEntity().setResourceBuildingsMap(resSre);


            resourceRepository.saveAndFlush(resourceRes.getResourceEntity());

            Map map = new HashMap();
            map.put("code", Code.CodeEnum.getCodeByType("OK"));
            map.put("map", resSre);
            map.put("total", resourceStatusStr);

            return map;
        }

        // get resource info in db
        ResourceEntity resource = resourceRepository.findByPlayerId(user.getId());
        if (resource == null) {
            Map map = new HashMap();
            map.put("code", Code.CodeEnum.getCodeByType("RESOURCE_NOT_EXIST"));
            map.put("msg", "resource info not exist");

            return map;
        }

        // set resource info in cache
        resourceController.setResourceEntities(resource);


        String resSre = resourceController.getResourceBuildingsMap(resource);

        resource.setResourceBuildingsMap(resSre);


        // get and check resourceBuildings build status
        String resourceStatusStr = resourceController.getResourceBuildingsStatus(resource.getResourceBuildingsMap());


        resourceRepository.saveAndFlush(resource);

        Map map = new HashMap();
        map.put("code", Code.CodeEnum.getCodeByType("OK"));
        map.put("map", resSre);
        map.put("total", resourceStatusStr);
        return map;
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public @ResponseBody NormRes createResource(@RequestBody ResourceReq resourceReq) throws JSONException {

        NormRes normRes;

        normRes = Utils.checkToken(request.getHeader("access-token"));

        int code = normRes.getCode();
        if (code != 200) {
            return normRes;
        }

        String resourceTypeStr = resourceReq.getResourceType();
        if (resourceTypeStr == null) {

            normRes = new NormRes(Code.CodeEnum.getCodeByType("RESOURCE_TYPE_EMPTY"), "resource type empty");

            return normRes;
        }


        // get user info
        String UserName = normRes.getMsg();

        UserController userController = UserController.UserControllerShared();
        UserEntity user = userController.getUserByUserName(UserName);
        if (user == null) {
            normRes = new NormRes(Code.CodeEnum.getCodeByType("USER_NOT_EXIST"), "user info not exist");
            return normRes;
        }


        // get resource info in cache
        ResourceEntity resource = null;
        ResourceController resourceController = ResourceController.resourceControllerShared();

        ResourceRes resourceRes = resourceController.getResourceEntitiesByPlayerId(user.getId());
        if (resourceRes == null) {

            // get resource info in db
            resource = resourceRepository.findByPlayerId(user.getId());
            if (resource == null) {
                normRes = new NormRes(Code.CodeEnum.getCodeByType("RESOURCE_NOT_EXIST"), "resource not exist");

                return normRes;
            }
        } else {
            resource = resourceRes.getResourceEntity();
        }


        normRes = resourceController.createResource(resource, resourceTypeStr);

        // save resource info to db
        resourceRepository.saveAndFlush(resource);

        return normRes;

    }

    @RequestMapping(value = "/completeCreate", method = RequestMethod.PUT)
    public @ResponseBody NormRes completeCreate() throws JSONException {
        NormRes normRes = null;

        normRes = Utils.checkToken(request.getHeader("access-token"));

        int code = normRes.getCode();
        if (code != 200) {
            return normRes;
        }



        // get user info
        String UserName = normRes.getMsg();

        UserController userController = UserController.UserControllerShared();
        UserEntity user = userController.getUserByUserName(UserName);
        if (user == null) {
            normRes = new NormRes(Code.CodeEnum.getCodeByType("USER_NOT_EXIST"), "user info not exist");
            return normRes;
        }

        ResourceController resourceController = ResourceController.resourceControllerShared();
        ResourceEntity resourceEntity = resourceController.getResourceEntitieByPlayerId(user.getId());

        String res = resourceController.getResourceBuildingsMap(resourceEntity);

        resourceRepository.saveAndFlush(resourceEntity);

        normRes = new NormRes(Code.CodeEnum.getCodeByType("OK"), res);
        return normRes;
    }

    @RequestMapping(value = "/createBuildings", method = RequestMethod.POST)
    public @ResponseBody Map createBuilding(@RequestBody String buildingType) throws JSONException {

        NormRes normRes;
        normRes = Utils.checkToken(request.getHeader("access-token"));

        Map resMap = new HashMap();

        int code = normRes.getCode();
        if (code != 200) {

            resMap.put("code", code);
            resMap.put("msg", normRes.getMsg());

            return resMap;
        }

        if (buildingType == null) {

            resMap.put("code", Code.CodeEnum.getCodeByType("RESOURCE_TYPE_EMPTY"));
            resMap.put("msg", "resource type empty");

            return resMap;
        }


        // get user info
        String UserName = normRes.getMsg();

        UserController userController = UserController.UserControllerShared();
        UserEntity user = userController.getUserByUserName(UserName);
        if (user == null) {

            resMap.put("code", Code.CodeEnum.getCodeByType("USER_NOT_EXIST"));
            resMap.put("msg", "user info not exist");

            return resMap;
        }


        // get resource info in cache
        ResourceEntity resource = null;
        ResourceController resourceController = ResourceController.resourceControllerShared();

        ResourceRes resourceRes = resourceController.getResourceEntitiesByPlayerId(user.getId());
        if (resourceRes == null) {

            // get resource info in db
            resource = resourceRepository.findByPlayerId(user.getId());
            if (resource == null) {

                resMap.put("code", Code.CodeEnum.getCodeByType("RESOURCE_NOT_EXIST"));
                resMap.put("msg", "resource info not exist");

                return resMap;
            }
        } else {
            resource = resourceRes.getResourceEntity();
        }


        resMap = resourceController.createBuilding(resource, buildingType);

        return resMap;

    }

    @RequestMapping(value = "/buildings/{pageIndex}", method = RequestMethod.GET)
    public @ResponseBody Map getBuildings(@PathVariable("pageIndex") String pageIndex) {
        System.out.println(pageIndex);

        NormRes normRes;
        normRes = Utils.checkToken(request.getHeader("access-token"));

        Map resMap = new HashMap();

        int code = normRes.getCode();
        if (code != 200) {

            resMap.put("code", code);
            resMap.put("msg", normRes.getMsg());

            return resMap;
        }

        if (pageIndex == null) {

            resMap.put("code", Code.CodeEnum.getCodeByType("RESOURCE_TYPE_EMPTY"));
            resMap.put("msg", "resource type empty");

            return resMap;
        }


        // get user info
        String UserName = normRes.getMsg();

        UserController userController = UserController.UserControllerShared();
        UserEntity user = userController.getUserByUserName(UserName);
        if (user == null) {

            resMap.put("code", Code.CodeEnum.getCodeByType("USER_NOT_EXIST"));
            resMap.put("msg", "user info not exist");

            return resMap;
        }


        // get resource info in cache
        ResourceEntity resource = null;
        ResourceController resourceController = ResourceController.resourceControllerShared();

        ResourceRes resourceRes = resourceController.getResourceEntitiesByPlayerId(user.getId());

        resource = resourceRes.getResourceEntity();

        resMap.put("code", Code.CodeEnum.getCodeByType("OK"));
        resMap.put("data", resource.getBuildingsMap());

        return resMap;

    }

}
